<template>
  <div class="rule-details innerPageTable-out-flex">
    <div class="content_top">
      <Modal
        v-model="modal1"
        @on-cancel="cancel">
        <p slot="header">{{ titleModle }}</p>
        <Form :label-width="90" ref="passForm" :model="modal1Form">
          <Form-item label="备注/意见" :rules="{ required: true, message: '请输入备注/意见', trigger: 'blur' }" prop="messages">
            <Input type="textarea" v-model="modal1Form.messages" :rows="4"></Input>
          </Form-item>
        </Form>
        <div slot="footer">
          <Button type="primary" ghost @click="modal1 = false">取消</Button>
          <Button type="primary" @click="ok">确定</Button>
        </div>
      </Modal>
      <Modal
        v-model="modal2"
        title="驳回">
        <Form :label-width="90" ref="nopassForm" :model="modal2Form">
          <Form-item label="驳回节点" :rules="{required: true, message: '请选择驳回节点', trigger: 'change'}" prop="taskDefKeys">
            <Select v-model="modal2Form.taskDefKeys">
              <Option v-for="item in optionList"
                      :key="item.taskDefKey"
                      :value="item.taskDefKey">{{ item.taskNodeName }}
              </Option>
            </Select>
          </Form-item>
          <Form-item label="备注/意见" :rules="{required: true, message: '请输入备注/意见', trigger: 'blur'}" prop="messages">
            <Input type="textarea" v-model="modal2Form.messages" :rows="4"></Input>
          </Form-item>
        </Form>
        <div slot="footer">
          <Button type="primary" ghost @click="modal2 = false">取消</Button>
          <Button type="primary" @click="ok2">确定</Button>
        </div>
      </Modal>

      <div class="cus_titles">
        <span class="base"></span>
        规则组信息
        <div class="flowDiv">
          <div class="flowButn" type="text" @click="flowHandle" v-if="processId">流程跟踪
            <Icon type="ios-arrow-forward" />
          </div>
        </div>
      </div>
      <!-- <div class="flowDiv">
        <Button class="flowButn" type="text" @click="flowHandle" v-if="processId">流程跟踪<Icon type="ios-arrow-forward" /></Button>
      </div>
       -->

      <detail-form ref="formDetail" :form-data="searchData"
                   :is-disabled="!isShow1 && (title ==='详情信息' || title ==='详情信息(只读)' || title === '新建信息') || isDisabled1">
      </detail-form>
      <div class="cus_titles">
        <span class="rulebase"></span>
        规则明细
      </div>
      <InnerPageTable ref="listTable" :config="pageTableConfig" class="page_table">
        <div slot="table-bar" v-if="isDisableRulePage">
<!--          <Button @click.native="add" :disabled="!isShow1 && (title ==='详情信息' || title ==='详情信息(只读)' || title === '新建信息') || isDisabled1">新建</Button>
          <Button type="error" @click.native="deleteHandle('子表')" :disabled="!isShow1 && (title ==='详情信息' || title ==='详情信息(只读)' || title === '新建信息') || isDisabled1">删除</Button>-->

          <Button @click.native="add">新建</Button>
          <Button type="error" @click.native="deleteHandle('子表')">删除</Button>
          <Button v-show="false"></Button>
        </div>
<!--        <div slot="table-bar" v-if="!isDisabled1 && !(this.title ==='详情信息(只读)')">
          <Button @click.native="add">新建</Button>
          <Button type="error" @click.native="deleteHandle('子表')">删除</Button>
          <Button v-show="false"></Button>
        </div>-->
      </InnerPageTable>
    </div>
    <div class="btn_box" v-if="!isDisabled1">
      <Button type="primary" @click="saveInfo" v-if="isShow1  && this.title ==='新建信息' ">保存</Button>
<!--      <Button type="primary" @click="updateInfo" v-if="isShow1 && (this.title ==='详情信息' || this.title ==='详情信息(只读)')">-->
<!--        修改-->
<!--      </Button>-->
      <Button type="primary" @click="updateInfo" v-if="isShow1 && title !== '新建信息'">
        保存
      </Button>
      <Button type="primary" @click="submitHandle('提交')" v-if="isShow">提交</Button>
      <Button type="primary" @click="submitHandle2('重新提交')" v-if="isShow2">重新提交</Button>
      <!-- <Button type="primary" @click="flowHandle" v-if="processId">流程</Button> -->
      <Button type="primary" @click="pressHandle('审核')" v-if="isShow3">审核</Button>
      <Button type="primary" @click="backHandle" v-if="isShow3">驳回</Button>
      <Button type="primary" @click="backHandle1" v-if="isShow4">撤回</Button>
      <Button type="default" @click.native="backHandle2">返回</Button>
    </div>
    <!-- 功能按钮群 -->
    <div v-else class="btn_box">
      <Button type="primary" @click="jumpAdd(detailId)" v-if="this.userId == this.createUserId">变更</Button>
      <Button type="default" @click.native="backHandle2">返回</Button>
    </div>
  </div>
</template>

<script>
import DetailForm from "./DetailForm";
import addModal from "./AddModal";
import flowImage from "@/components/flowImage";
import listDetails from "./ListDetails.vue";

import { configForm, generateColumns, ruleValidate } from "./detail-constants";
import ruleBaseAPI from "@/api/ruleBaseApi.js";
import ruleListAPI from "@/api/ruleListApi.js";
import todoListAPI from "@/api/todoListApi.js";
import { mixin } from "../mix/mixin";

export default {
  name: "rule-details",
  mixins: [mixin],
  components: {
    detailForm: DetailForm,
    addModal,
    listDetails
    // processes
  },
  props: {
    title: {
      type: String,
      default: ""
    },
    codeInt: {
      type: String,
      default: ""
    },
    idInt: {
      type: String,
      default: ""
    },
    detailId: {
      type: String,
      default: ""
    },
    groupCode: {
      type: String,
      default: ""
    },
    bpmnState: {
      type: Number,
      default: null
    },
    isDisabled: {
      type: Boolean,
      default: false
    },
    isDisabled1: {
      type: Boolean,
      default: false
    },
    rowDetail: {},
    route: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      isSubmitDisabled: false,
      ruleValidate: ruleValidate,//form 效验
      titleModle: "",//按钮弹窗标题
      modal1: false,
      modal2: false,
      optionList: [],      // 流程节点
      pageTableConfig: {
        loadDataFn: this.getTableList,
        columns: generateColumns.bind(this)(),
        autoFirst: false,
        autoMaxHeight: false,//关于高度
        selectionAreaItem: { key: "id", title: "userName" },
        allSelection: [],
        initParam: {
          "describes": "",
          "groupCodeList": [],
          "idList": [],
          "parentList": [],
          "ruleIdentifyColumn": "",
          "ruleTableName": "",
          "stateList": [],
          "title": ""
        }
      },
      detailInfo: [],
      formValidate: {},
      processId: "",//流程id

      pressesData: null,//获取接口的流程数据
      taskId: "",//审核需要传的参数id
      modal1Form: {
        messages: "",//审核需要传的参数意见
      },
      modal2Form: {
        messages: "",//驳回需要传的参数意见
        taskDefKeys: "",//驳回需要传的参数
      },
      taskNodeData: null,//获取可驳回的流程节点
      // 控制按钮显示
      isUndo: true,//判断能否撤回流程
      userIds: [],
      userId: "",//当前用户的id
      createUserId: "",
      optionListN: []
    };
  },
  computed: {
    // ...mapState('sasspWeb', state),
    searchData() {
      const arr = configForm.bind(this)()
      if (this.route === 'rule-list') {
        const index = arr.findIndex(item => item.field === 'bpmnState')
        if (index > -1) {
          arr.splice(index, 1)
        }
      }
      return arr
    },

    optionListUnit() {
      return this.optionListN;
    },
    //是否展示提交按钮
    isShow() {
      return this.bpmnState == null && this.processId == null && this.userId == this.createUserId;
    },
    //是否展示保存（修改）按钮
    isShow1() {
      return (this.codeInt || this.bpmnState == null && this.userId == this.createUserId) || (this.bpmnState === 1 && !!this.pressesData && this.pressesData.taskDefKey === "start_task_user_activity" && this.userIds.includes(this.userId));
    },
    //是否展示重新提交按钮
    isShow2() {
      return this.bpmnState === 1 && this.processId != null && !!this.pressesData && this.pressesData.taskDefKey === "start_task_user_activity" && this.userIds.includes(this.userId);
    },
    //是否展示审批、驳回按钮
    isShow3() {
      return this.bpmnState === 1 && this.processId != null && !!this.pressesData && this.pressesData.taskDefKey != "start_task_user_activity" && this.userIds.includes(this.userId);
    },
    //撤回
    isShow4() {
      return this.bpmnState === 1 && this.processId != null && this.userId == this.createUserId && !!this.pressesData && this.pressesData.taskDefKey != "start_task_user_activity" && this.isUndo;
    },
    isDisableRulePage() {
      return ((this.pressesData && this.pressesData.taskDefKey === 'sassp_rule_skxmzsh_task') && this.userIds.includes(this.userId)) && this.route !== 'rule-list'
    }
  },
  created() {
    this.init();
  },
  mounted() {
    if (this.route === 'rule-list') {
      this.$refs.listTable.load(this.pageTableConfig.initParam)
    }
  },
  methods: {
    init() {
      this.$emit("SetTitle", this.title);
      //获取用户id
      $http.post("/apis/mgt/security/getLoginData").then(res => {
        this.userId = res.data.userBasicVo.id;
        // 获取用户信息
        ruleBaseAPI.detailUserInfo({ id: this.userId }).then(res => {
          let crsrmPurchaser_Name = [];
          let crsrmPurchaser_Sbu = [];
          crsrmPurchaser_Sbu = this.getTaskId(res.data.crsrmPurchaserSbu);

          crsrmPurchaser_Sbu.forEach(item => {
            this.optionListN.push({
              label: this.crsrm_purchaser_sbu.find(x => x.value === item).label,
              value: item
            });
          });
        });
      });

      //如果是详情进入时
      if (this.rowDetail && this.detailId) {
        this.detailInit();
      } else {
        //新建页面生成的编码
        this.searchData.forEach((item, index) => {
          if (item.field == "code") {
            item.value = this.codeInt;
          }
        });
      }
    },
    // 页面刷新
    refresh() {

    },
    //字符串转数组的方法
    getTaskId(taskIds) {
      // return taskIds.split(',')[0]
      return taskIds.split(",");
    },
    getTableList(tableObj) {
      let { responseProcess, initParam, param } = tableObj;
      const params = {
        ...param,
        ...initParam
      };
      if (!this.detailId && !this.groupCode) {
        //新建时-->获取表数据
        this.pageTableConfig.initParam.parentList.push(this.idInt);
        ruleBaseAPI.queryDetails(params).then(res => {
          responseProcess(res.data);
        });
      }
      if (this.title === "详情信息" || this.title === "详情信息(只读)") {
        //详情时-->获取表数据
        this.pageTableConfig.initParam.parentList.push(this.detailId);
        ruleBaseAPI.queryDetails(params)
          .then(res => {
            // if (this.title === "详情信息(只读)") {
            if (!this.isDisableRulePage) {
              //用户不可选
              // console.log(res.data)
              res.data.records.forEach(item => {
                item._disabled = true;
              });
              responseProcess(res.data);
            } else {
              responseProcess(res.data);
            }
          });
      }
      if (this.title === "列表详情(只读)") {
        //规则库列表--》详情时-->获取表数据
        this.pageTableConfig.initParam.parentList.push(this.detailId);
        ruleListAPI.getScriptPage(params).then(res => {
          //用户不可选
          // console.log(res.data)
          res.data.records.forEach(item => {
            item._disabled = true;
          });
          responseProcess(res.data);
        });
      }

    },
    //数组转对象方法
    arrobj(formData) {
      return formData.reduce((obj, item) => {
        obj[item.field] = item.value;
        return obj;
      }, {});
    },
    //规则维护 返回按钮
    backHandle2() {
      this.$emit("Close");
    },
    detailInit() {
      this.searchData.forEach((item, index) => {
        for (let i in this.rowDetail) {
          if (item.field == i) {
            item.value = this.rowDetail[i] + "";
          }
        }
      });
      this.processId = this.rowDetail.processId;
      this.createUserId = this.rowDetail.createUserId;
      if (this.processId) {
        //查询流程实例最新的节点id和任务处理人
        todoListAPI.processNode({ id: this.processId }).then(res => {
          if (res.data != null) {
            this.pressesData = res.data;
            this.userIds = this.getTaskId(this.pressesData.userIds);
            this.taskId = this.getTaskId(res.data.taskIds)[0];
          } else {
            this.pressesData ? this.pressesData.taskDefKey = 'end' : ''
            // this.$set(this.pressesData, 'taskDefKey', 'end')
          }
          this.$refs.listTable.load(this.pageTableConfig.initParam)
        });
        //查询可以退回的流程节点
        if (this.rowDetail.bpmnState != 2) {

          todoListAPI.processRejectNode({ id: this.processId }).then(res => {
            this.taskNodeData = res.data;
            this.optionList = this.taskNodeData;
          });
        }

        //判断能否撤回流程
        todoListAPI.processUndoCheck({ id: this.processId }).then(res => {
          this.isUndo = res.data;
        });
      } else {
        this.$nextTick(() => {
          this.$refs.listTable.load(this.pageTableConfig.initParam)
        })
      }
    },
    saveInfo() {
      this.$refs.formDetail.$refs.createForm.validate((valid) => {
        if (valid) {
          const dataForm = this.$refs.formDetail.detailData.formData;
          this.formValidate = this.arrobj(dataForm);
          // this.formValidate = this.arrobj(this.searchData)
          this.$confirm.warning(this.$t("确定新建吗？")).then(() => {
            if (!this.detailId && !this.groupCode) {
              // this.formValidate.idList = [this.idInt]
              this.formValidate.id = this.idInt;
              ruleBaseAPI.createList(this.formValidate).then(res => {
                this.$message.success({
                  content: this.$t("新建成功"),
                  duration: 3
                });
                this.saveRefresh(res.data, false);
                /*                this.resetHandle()
                                this.backHandle2()*/
              });
            }
          });
          // this.$message.success('Success!');
        } else {
          this.$message.error("检查是否完整填写相关内容！！");
        }
      });

    },
    saveRefresh(res) {
      let detailId = this.detailId ? this.detailId : res.id;
      let params = {
        "codeList": [],
        "dataItemName": "",
        "dataSubject": "",
        "describes": "",
        "functionModules": "",
        "idList": [],
        "stateList": [],
        "title": ""
      };
      params.idList.push(detailId);
      ruleBaseAPI.queryList1(params).then(res => {
        this.rowDetail = res.data[0];
        this.detailId = this.rowDetail.id;
        this.title = "详情信息";
        this.groupCode = this.rowDetail.code;
        this.codeInt = ''
        // this.isDisabled = this.rowDetail.bpmnState
        this.bpmnState = this.rowDetail.bpmnState
        this.detailInit();
      });
    },
    //详情时--修改
    updateInfo() {
      this.$refs.formDetail.$refs.createForm.validate((valid) => {
        if (valid) {
          const dataForm = this.$refs.formDetail.detailData.formData;
          this.formValidate = this.arrobj(dataForm);
          // this.formValidate = this.arrobj(this.searchData)
          this.$confirm.warning(this.$t("确定修改吗？")).then(() => {
            if (this.detailId && this.groupCode) {
              this.formValidate.version = this.rowDetail.version;
              this.formValidate.id = this.detailId;
              ruleBaseAPI.updateList(this.formValidate).then(res => {
                this.$message.success({
                  content: this.$t("修改成功"),
                  duration: 3
                });
                // this.backHandle2();
                this.saveRefresh(res)
              });
            }
          });
        } else {
          this.$message.error("检查是否完整填写相关内容！！");
        }
      });


    },


    ok() {
      let params = {
        "message": this.modal1Form.messages,
        "taskId": this.taskId,
        "values": {}
      };
      this.$refs.passForm.validate(valid => {
        if (valid) {
          if (this.titleModle == "审核") {
            todoListAPI.processPass(params).then(res => {
              this.$message.success('操作成功');
              this.saveRefresh(res)
              this.modal1 = false
            });
            // this.backHandle2();
          }
          if (this.titleModle == "重新提交") {
            // this.$confirm.warning(this.$t("确定重新提交吗？")).then(() => {
              todoListAPI.processSubmit(params).then(res => {
                this.$message.success('操作成功');
                this.saveRefresh(res)
                this.modal1 = false
              });
              // this.backHandle2();
            // });
          }
        } else {
          return false
        }
      })

    },
    cancel() {
    },
    ok2() {
      let params = {
        "id": this.detailId,
        "type": "rule",
        "message": this.modal2Form.messages,
        "procInstId": this.processId,
        "taskDefKey": this.modal2Form.taskDefKeys

      };
      this.$refs.nopassForm.validate(valid => {
        if (valid) {
          this.$confirm
            .warning(this.$t("确定驳回吗？")).then(() => {
            todoListAPI.processReject(params).then(res => {
              this.$message.success('操作成功');
              this.saveRefresh(res)
              this.modal2 = false
            });
            // this.backHandle2();
          });
        }
      })
    },
    //重新提交
    submitHandle2(titleModle) {
      this.$refs.formDetail.$refs.createForm.validate((valid) => {
        if (valid) {
          this.titleModle = titleModle;
          this.modal1 = !this.modal1;
          // this.isSubmitDisabled = !this.isSubmitDisabled;

        } else {
          this.$message.error("检查是否完整填写相关内容！！");
        }
      });

    },
    //提交按钮事件
    submitHandle(titleModle) {
      this.$refs.formDetail.$refs.createForm.validate((valid) => {
        if (valid) {
          const params = {
            "describes": this.rowDetail.describes,
            "id": this.detailId,
            "taskId": this.rowDetail.taskId
          };
          if (!this.detailId && !this.groupCode) {
            params.id = this.idInt;
          } else {
            params.id = this.detailId;
          }
          this.$confirm
            .warning(this.$t("确定提交吗？")).then(() => {
            ruleBaseAPI.submitList(params).then(res => {

              this.$message.success({
                content: this.$t("提交成功"),
                duration: 3
              });
              this.saveRefresh(res)
              // this.backHandle2();
            });

          });

        } else {
          this.$message.error("检查是否完整填写相关内容！！");
        }
      });


    },
    // 驳回按钮事件
    backHandle() {
      this.modal2 = !this.modal2;
    },

    // 审核按钮事件
    pressHandle(titleModle) {
      this.titleModle = titleModle;
      this.modal1 = !this.modal1;

    },
    // 撤回
    backHandle1() {
      if (this.isUndo) {
        this.$confirm
          .warning(this.$t("确定撤回吗？")).then(() => {
          todoListAPI.processUndo({ id: this.processId }).then(res => {
            this.saveRefresh(res)
          });
        });
        // this.backHandle2();
      }
    },
    //流程历史
    flowHandle() {
      new this.$pageModal(flowImage, { props: { id: this.rowDetail.processId } });
    },
    //新建子表
    add() {
      //新建页面---->新建按钮
      if (!this.detailId && !this.groupCode) {
        new this.$pageModal(
          addModal, { props: { codeInt: this.codeInt, parent: this.idInt, title: "新建" } },
          () => {
            this.resetHandle();
          }
        );
      } else {
        //详情页面---->新建按钮
        new this.$pageModal(
          addModal,
          {
            props: { groupCode: this.groupCode, parent: this.detailId, title: "新建(详情)"}
          },
          () => {
            this.resetHandle();
          }
        );
      }

    },

    // 删除子表
    // del() {
    //   let allSelected = this.$refs["listTable"].allSelection;
    //   if (allSelected.length == 0) {
    //     this.$message.error(this.$t("请至少选择一套数据"));
    //     return;
    //   }
    //   this.$confirm
    //     .warning(this.$t("确定删除后，无法恢复！"))
    //     .then(() => {
    //       const idList = allSelected.map(user => user.id);
    //       ruleBaseAPI.deleteDetails({idList}).then(res => {
    //         this.$message.success({
    //           content: this.$t("删除成功"),
    //           duration: 3
    //         });
    //         this.$refs["listTable"].allSelection = [];
    //         this.searchHandle()
    //       });

    //     }).catch(_ => _);
    // },
    //详情
    detailHandle(row) {
      let detailRow = row;
      let detailId = row.id;
      let groupCode = row.code;
      // 查询
      let params = {
        "codeList": [],
        "dataItemName": "",
        "dataSubject": "",
        "describes": "",
        "functionModules": "",
        "idList": [],
        "stateList": [],
        "title": ""
      };
      params.idList.push(detailId);
      if (this.isDisabled1 || this.title === "列表详情(只读)") {
        ruleListAPI.getScriptList(params).then(res => {
          detailRow = res.data[0];
        });
        new this.$pageModal(
          // addModal, { props: { detailRow, detailId, groupCode, isDisabled: !this.isShow1 || this.isDisabled1, title: "详情(只读)" } },
          addModal, { props: { detailRow, detailId, groupCode, isDisabled: !this.isDisableRulePage, title: "详情(只读)" } },
          // 关闭时的回调
          () => {
            this.resetHandle();
          }
        );
      } else {
        ruleBaseAPI.queryList2(params).then(res => {
          detailRow = res.data[0];
        });
        new this.$pageModal(
          addModal, { props: { detailRow, detailId, groupCode, isDisabled: !this.isDisableRulePage, title: "详情" } },
          // 关闭时的回调
          () => {
            this.resetHandle();
          }
        );
      }
    },
    //规则列表跳转到新建按钮事件
    async jumpAdd(id) {
      //生成主键id
      let applicationIdResponse = await ruleBaseAPI.buildId();
      let applicationId = applicationIdResponse.data;
      //获取规则脚本黄金记录
      let ruleScriptGoldListResponse = await ruleListAPI.getScriptList({ parentList: [id] });
      let ruleScriptGoldList = ruleScriptGoldListResponse.data;
      //获取规则组黄金记录
      let ruleGroupGoldListResponse = await ruleListAPI.getGroupList({ idList: [id] });
      let ruleGroupGold = ruleGroupGoldListResponse.data[0];
      //去除多余字段
      ruleScriptGoldList.forEach(v => {
        v.parent = applicationId;
        v.id = null;
        v.updateTime = null;
        v.updateUserId = null;
        v.createUserId = null;
        v.createTime = null;
        v.version = null;
      });
      //批量创建
      if (ruleScriptGoldList.length>0) {
         await ruleBaseAPI.addScriptBpmnList({ "list": ruleScriptGoldList })
      }

      //更新规则组黄金记录并跳转
      ruleGroupGold.id = applicationId;
      ruleGroupGold.updateTime = null;
      ruleGroupGold.updateUserId = null;
      ruleGroupGold.createUserId = null;
      ruleGroupGold.createTime = null;
      ruleGroupGold.version = null;
      new this.$sidelipPage(
        listDetails,
        {
          props: { rowDetail: ruleGroupGold, idInt: ruleGroupGold.id, codeInt: ruleGroupGold.code, detailId: this.detailId, title: "跳转新建"},
          isNav: false
        },
        () => {
          // 关闭时的回调
          // this.resetHandle()
        }
      );
    }

  }
};

</script>

<style lang="less" scoped>
.rule-details {
  height: 100%;

  .content_top {
    height: calc(100% - 50px) !important;
    overflow-y: scroll;
  }
}

.cus_titles {
  display: flex;
  align-items: center;
  padding: 0 10px;
  height: 40px;
  line-height: 40px;

  font-size: 14px;
  color: #262626;
  letter-spacing: 0;
  text-align: left;
  font-weight: 400;
  background: #F8F9FB;
  position: relative;

  .base {
    width: 17px;
    height: 18px;
    margin-right: 10px;
    background: url("../../../asset/icons/rulebase.svg") no-repeat center;
    background-size: cover;
  }

  .rulebase {
    width: 17px;
    height: 18px;
    margin-right: 10px;
    background: url("../../../asset/icons/rulebase1.svg") no-repeat center;
    background-size: cover;
  }
}

.page_table {
  min-height: 500px !important;
}

.flowDiv {
  position: absolute;
  right: 15px;
  text-align: end;
  margin-bottom: 5px;

  .flowButn {
    color: #2d8cf0;
  }
}

.btns {
  display: flex;
  justify-content: end;
}

.btn_box {
  text-align: right;
  margin-right: 60px;
  //position: fixed;
  //bottom: 15px;
  //right: 50px;
  background: #ffffff;
  z-index: 1000 !important;
}

.btn_box > * {
  margin-left: 10px;
  margin-bottom: 5px;
}
/deep/.ivu-input[disabled], /deep/.ivu-select-disabled .ivu-select-selection, /deep/.ivu-select-single{
  color: #666F83 !important;
}
</style>


